﻿CREATE PROCEDURE state_Loan_ToRepo
	@LoanID int,
	@RepoStatusID int
AS
SET NOCOUNT ON

--SELECT NS.StateToID,S.Name
UPDATE C SET StatusID = NS.StateToID
FROM t_Collection C
CROSS APPLY
fs_NextStates(ISNULL(C.StatusID,dbo.fs_StateID__Collection__Start())) NS 
WHERE C.LoanID = @LoanID AND NS.StateToID = @RepoStatusID

DECLARE @RC int SET @RC = @@ROWCOUNT

IF @RC > 1 BEGIN
	ROLLBACK TRAN
	RAISERROR('Multiple update while changing status in Collection. LoanID:%d.',16,1,@LoanID)
	RETURN
END
IF @RC = 1 RETURN

IF EXISTS(SELECT * FROM t_Collection WHERE LoanID = @LoanID)BEGIN
	ROLLBACK TRAN
	DECLARE @Status sysname SELECT @Status = Status FROM v_Collection WHERE LoanID = @LoanID
	RAISERROR('This result code is not availible while loan is in [%s] status.',16,1,@Status)
	RETURN
END

INSERT INTO t_Collection(LoanID,StatusID)VALUES(@LoanID,@RepoStatusID)



